package com.hui.dbmigrator.handler;

import com.hui.dbmigrator.config.DatabaseConfig;
import com.hui.dbmigrator.entity.TableDefinition;
import com.hui.dbmigrator.service.TypeConversionService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class MySQLHandler extends AbstractDatabaseHandler implements DatabaseHandler {

    private final TypeConversionService typeConversionService;

    @Override
    public String getDatabaseType() {
        return "MySQL";
    }

    @Override
    public String generateCreateTable(TableDefinition table) {
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE ").append(quoteIdentifier(table.getName())).append(" (\n");

        // Columns
        List<String> columnDefs = table.getColumns().stream()
                .map(this::generateColumnDefinition)
                .collect(Collectors.toList());

        // Primary Keys
        String pkColumns = table.getColumns().stream()
                .filter(TableDefinition.ColumnDefinition::isPrimaryKey)
                .map(col -> quoteIdentifier(col.getName()))
                .collect(Collectors.joining(", "));

        if (!pkColumns.isEmpty()) {
            columnDefs.add("  PRIMARY KEY (" + pkColumns + ")");
        }

        sql.append(String.join(",\n", columnDefs));
        sql.append("\n)");

        // Table options
        appendTableOptions(sql, table);

        return sql.toString();
    }

    /**
     * 生成列定义SQL片段
     */
    private String generateColumnDefinition(TableDefinition.ColumnDefinition column) {
        StringBuilder def = new StringBuilder("  ");
        def.append(quoteIdentifier(column.getName())).append(" ").append(column.getType());

        // NULL/NOT NULL
        if (!column.isNullable()) {
            def.append(" NOT NULL");
        }

        // 默认值
        if (column.getDefaultValue() != null) {
            def.append(" DEFAULT ").append(formatDefaultValue(column.getDefaultValue(), column.getType()));
        }

        // 自增 (AUTO_INCREMENT)
        if (column.isAutoIncrement()) {
            def.append(" AUTO_INCREMENT");
        }

        // 注释
        if (StringUtils.isNotBlank(column.getComment())) {
            def.append(" COMMENT '").append(escapeSqlString(column.getComment())).append("'");
        }

        return def.toString();
    }

    /**
     * 添加表选项（ENGINE/CHARSET等）
     */
    private void appendTableOptions(StringBuilder sql, TableDefinition table) {
        if (StringUtils.isNotBlank(table.getEngine())) {
            sql.append(" ENGINE=").append(table.getEngine());
        }
        if (StringUtils.isNotBlank(table.getCharset())) {
            sql.append(" DEFAULT CHARSET=").append(table.getCharset());
        }
        if (StringUtils.isNotBlank(table.getComment())) {
            sql.append(" COMMENT='").append(escapeSqlString(table.getComment())).append("'");
        }
    }

    /**
     * 转义SQL字符串中的特殊字符
     */
    private String escapeSqlString(String input) {
        return input.replace("'", "''")
                .replace("\\", "\\\\");
    }

    // 其他必须实现的方法...
    @Override
    public String generateAlterTable(String tableName, List<String> alterStatements) {
        return "ALTER TABLE " + quoteIdentifier(tableName) + " " +
                String.join(", ", alterStatements);
    }

    @Override
    public TableDefinition extractTable(String tableName, DatabaseConfig config) throws SQLException {
        // 实现元数据提取逻辑
        return null;
    }

    @Override
    public List<String> getTableNames(DatabaseConfig config) throws SQLException {
        // 实现获取表名列表逻辑
        return new ArrayList<>();
    }

    @Override
    public void execute(DatabaseConfig config, String sql) throws SQLException {
        // 实现SQL执行逻辑
    }
}
